package com.itheima.exerciseTest.method40_49.method49;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

public class ThreadServer implements Runnable {
    private Socket accept;

    public ThreadServer(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        BufferedWriter bw2 = null;
        try {
            // 连接成功 给客户端响应
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(accept.getOutputStream()));
            bw.write("欢迎光临！请上传文件(文本文件)！");
            bw.newLine();
            bw.flush();

//            // 接收客户端文件并保存在本地
//            BufferedReader br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
//            bw2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\aheima\\模拟考试\\考试\\试题B\\接收文件\\" + UUID.randomUUID().toString() + ".txt"),"UTF-8"));
//            String str;
//            while ((str = br.readLine()) != null) {
//                str = str.replace("操", "**");
//                bw2.write(str);
//                bw2.newLine();
//                bw2.flush();
//            }
            BufferedInputStream bis = new BufferedInputStream(accept.getInputStream());
            bw2 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("D:\\aheima\\模拟考试\\考试\\试题B\\接收文件\\" + UUID.randomUUID().toString() + ".txt"),"UTF-8"));
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                bw2.write(new String(bytes,0,len));
            }

            // 返回客户端响应
            bw.write("上传成功！");
            bw.newLine();
            bw.flush();



        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bw2 != null){
                try {
                    bw2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(accept != null){
                try {
                    accept.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
